<template>
  <div class="Timeflow_statistics">

    <div class="tips">
      操作说明
      <a-tooltip placement="right">
        <template #title>
          <span>提供最新访客的来源、访问轨迹、地域、客户端等详细信息。助您了解当前的访客行为，及时根据访客特征优化网站。</span>
        </template>
        <span class="iconfont icon-hint1"></span>
      </a-tooltip>
    </div>
    <div class="selectSite">
      <!-- <span>站点选择：</span>
      <a-select v-model:value="sectionValue" placeholder="请选择"
        :options="sectionOptions.map((item: any) => ({ value: item.id, label: item.siteName }))"
        @change="handleChange"></a-select> -->
      <getSite @handleChange="handleChangeSite" ref="getSite_ref"></getSite>
    </div>
    <div class="online">
      <div class="currentOnline">
        当前在线
        <span class="time">{{ time }}秒 </span>
        <span class="updateTips">后更新数据</span>
      </div>
      <div class="currentOnline_bottom">
        <div class="currentOnline_bottom_left">
          <div class="updateTime">
            {{ updateTime }}
          </div>
          <h2>{{ onlineNumber }}</h2>
          <div>在线访客数</div>
        </div>
        <div class="currentOnline_bottom_right">
          <h2>最近30分钟访问情况</h2>
          <div id="timeOnline"></div>
        </div>
      </div>
    </div>
    <div class="visitDetail">
      <div class="visitDetail_header">
        <div class="from item">
          <span>来源：</span>
          <a-select v-model:value="formData.fromSectionValue" placeholder="请选择"
            :options="formData.fromSectionOption.map((item: any) => ({ value: item.value, label: item.label }))"
            @change="handleChange"></a-select>
        </div>
        <div class="timeSelect">
          <!-- 所属时间模块部分 -->
          <commonDatePick :formData='formData' @select-type="selectType" @selectTimeChange="selectTimeChange"  ref="commonDatePick_ref"></commonDatePick>
        </div>
        <div class="visitTimeRange item" v-if="isOpen">
          <!-- 所属用户类型模块部分 -->
          <section class="options">
            <span class="options_label">访问时长:</span>
            <a-select v-model:value="formData.visitTimeSectionValue" placeholder="请选择"
              :options="formData.visitTimeSectionOption.map((item: any) => ({ value: item.value, label: item.label }))"
              @change="handleChange"></a-select>
          </section>
        </div>
        <div class="visitorTypeSelect item" v-if="isOpen">
          <!-- 所属访客类型模块部分 -->
          <section class="options">
            <span class="options_label">访客:</span>
            <div class="options_content">
              <span v-for="item in formData.selectVisitorTypeOption" :key="item.value"
                :class="formData.selectVisitorType === item.value ? 'activeOption' : ''"
                @click="selectType(item, 'selectVisitorType')">{{
                  item.label
                }}</span>
            </div>
          </section>
        </div>
        <div class="userTypeSelect item" v-if="isOpen">
          <!-- 所属用户类型模块部分 -->
          <section class="options">
            <span class="options_label">用户:</span>
            <div class="options_content">
              <span v-for="item in formData.userOptions" :key="item.value"
                :class="formData.userSelectOptions === item.value ? 'activeOption' : ''"
                @click="selectType(item, 'userSelectOptions')">{{
                  item.label
                }}</span>
            </div>
          </section>
        </div>
        <div class="area item" v-if="isOpen">
          <getArea @handleChange="handleChange" ref="getArea_ref">
          </getArea>
        </div>
        <div class="option-content">
          <!-- <a-button @click="resetOptions">重置</a-button> -->
          <!-- <a-button :style="{ 'margin-right': '8px' }" class="addButton" type="primary"
            @click="getVisitList()">搜索</a-button> -->
          <div class="openorclose" @click="() => isOpen = true" v-if="!isOpen">
            <a>展开</a>
            <i class="iconfont icon-down" style="font-size: 24px"> </i>
          </div>
          <div class="openorclose" @click="() => isOpen = false" v-if="isOpen">
            <a>收起</a>
            <i class="iconfont icon-up" style="font-size: 24px"> </i>

          </div>
        </div>
      </div>
      <!-- 表格展示部分 -->
      <baseTable :columns="columns.flowColumns" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
        ref="sensitiveBaseTables" :isShowPagination="isShowPagination" :rowSelection="1" :total="configData.total"
        @changePage="changePage">
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.ellipsis">
            <table-tool-tip :text="text" :column="column"></table-tool-tip>
          </template>
          <!-- <template v-if="column.dataIndex == 'sourceUrl'">
            <a class="sourceUrl">{{ text }}</a>
          </template> -->

        </template>
      </baseTable>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, onBeforeMount, onUnmounted, reactive, watch, computed } from "vue";
import request from "@/api/index";
import getters from "@/store/getters";
import { initEcharts } from "@/components/echarts/index";
import { optionBar } from "./echartType/options";
import columns from "@/components/table/tableConfig/tableColumn/siteStatistics";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import commonDatePick from '../commonHeader/date.vue';
import getSite from '../commonHeader/getSite.vue';
import getArea from '../commonHeader/area.vue';
// type flowColumns
interface dataSourceType {
  [propName: string]: any;
}
//getters
const userInfo = getters.userInfo();
//data
const sectionValue = ref(userInfo.siteId);
const time = ref(0);
const updateTime = ref((new Date()).toLocaleString().replace(/\//g, '-'));
const onlineNumber = ref(0);
const dataSource = ref<dataSourceType>(JSON.parse(JSON.stringify(optionBar)));
dataSource.value.legend.data = ['浏览量(PV)', '访客数(UV)'];
dataSource.value.series[0].name = '浏览量(PV)';
dataSource.value.series[1].name = '访问数(UV)';
let Timer = ref<any>(null);
const getSite_ref = ref();
//表格展示

const commonDatePick_ref = ref();
let selectTimeRange = ref<(string | number)[]>([]); //选择时间范围
const isOpen = ref(false);


const formData = reactive<dataSourceType>({
  fromSectionValue: '', //来源
  fromSectionOption: [
    {
      label: '全部',
      value: ''
    }, {
      label: '搜索引擎',
      value: 1
    }, {
      label: '外部链接',
      value: 2
    }, {
      label: '直接访问',
      value: 3
    },
  ],
  selectTimeOption: 1,
  TimeOptions: [{
    label: '今天',
    value: 1
  }, {
    label: '昨天',
    value: 2
  }, {
    label: '最近7天',
    value: 3
  }, {
    label: '最近30天',
    value: 4
  }],
  visitTimeSectionValue: 1,//时间段筛选
  visitTimeSectionOption: [
    {
      label: '全部',
      value: ''
    }, {
      label: '0-60s',
      value: 1
    }, {
      label: '61-180s',
      value: 2
    }, {
      label: '181-300s',
      value: 3
    }, {
      label: '301-600s',
      value: 4
    },
    {
      label: '600s以上',
      value: 5
    },
  ],
  selectVisitorType: '',
  selectVisitorTypeOption: [
    {
      label: '全部',
      value: ''
    }, {
      label: '新访客',
      value: 0
    }, {
      label: '老访客',
      value: 1
    },
  ],
  userSelectOptions: '',//用户类型
  userOptions: [
    {
      label: '全部',
      value: ''
    }, {
      label: '登录用户',
      value: 0
    }, {
      label: '匿名用户',
      value: 1
    },
  ],
})
let selectAreaData = ref(null); // 选择区域
const getArea_ref = ref();
//表格数据
let configData = reactive<dataSourceType>({ total: 0, size: 10, records: [] });
let scroll: dataSourceType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
//分页
const pageNumber = ref(1);
const pageSize = ref(10);
// computed
selectAreaData = computed(() => getArea_ref.value?.selectAreaData || null);

//methods
const handleChangeSite = (value: any) => {//站点选择变化
  // 站点变化
  nextTick(() => {
    time.value = 0;
    sectionValue.value = getSite_ref.value.sectionValue;
    getOnlineVisitors();
    getVisitList();
  });
};
const handleChange = (value: any) => {//其他选择变化
  nextTick(() => {
    getVisitList();
  });
};
// 获取在线统计数据
const getOnlineVisitors = async () => {
  if (time.value > 0) {
    time.value--
  }
  else if (time.value == 0) {
    time.value = 300;
    let nowtime = new Date();
    updateTime.value = (nowtime.toLocaleString()).replace(/\//g, '-');
    let data: dataSourceType = {
      dateTime: updateTime.value,
      siteId: sectionValue.value,
    }
    await request.getOnlineVisitors(data).then((res: dataSourceType) => {
      onlineNumber.value = res.onlineVisitorsNum;
      let list = res.pvUvDtoList;
      dataSource.value.xAxis[0].data = [];

      list.forEach((item: dataSourceType) => {
        dataSource.value.xAxis[0].data.push(item.timeStr);
        dataSource.value.series[0].data.push(item.pvNum);
        dataSource.value.series[1].data.push(item.uvNum);
      });

    });
    nextTick(() => {
      initEcharts('timeOnline', dataSource.value);
    })
  } else {
    time.value = 300
  }

}
// 清空定时器
const handleClearInterval = () => {
  if (Timer.value) {
    clearInterval(Timer.value)
    Timer.value = null
  }
};
// 创建定时器
const createInterval = () => {
  if (!Timer.value) {
    Timer.value = setInterval(() => getOnlineVisitors(), 1000)
  }
}
//选择搜索项
const selectType = (item: dataSourceType, type: string) => {
  formData[type] = item.value;
  getVisitList();
}

const selectTimeChange = () => {
  selectTimeRange.value = commonDatePick_ref.value.selectTimeRange;
  getVisitList();
}

// 获取访问列表
const getVisitList = () => {
  nextTick(() => {
    selectTimeRange.value = commonDatePick_ref.value.selectTimeRange;
    let data = {
      startTime: selectTimeRange.value[0],
      endTime: selectTimeRange.value[1],
      logonStatus: formData.userSelectOptions,
      newVisitor: formData.selectVisitorType,
      pageAccessTimeType: formData.visitTimeSectionValue,
      pageNumber: pageNumber.value,
      pageSize: pageSize.value,
      province: selectAreaData.value,
      siteId: sectionValue.value,
      sourceUrlType: formData.fromSectionValue,
    }
    request.getVisitList(data).then((res: dataSourceType) => {
      configData.total = res.total;
      configData.records = res.records;
      configData.records.forEach((item: any, index: number) => {
        item.index = index + 1
        item.sourceUrlType = item.sourceUrlType === 1 ? '搜索引擎' : item.sourceUrlType === 2 ? '外部链接' : item.sourceUrlType === 3 ? '直接访问' : ''
      })
    })
  })

}
//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  let datas: dataSourceType = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  pageNumber.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  getVisitList();
};
//onMounted

onMounted(() => {
  createInterval();
  initEcharts('timeOnline', dataSource.value);
  getVisitList();
});
onUnmounted(() => {
  handleClearInterval();
});
</script>

<style lang="less" scoped>
.Timeflow_statistics {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background: #fff;
  overflow: auto;

  .tips {
    margin-bottom: 24px;
    font-size: 14px;
    color: #333;
  }



  .online {
    height: 350px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    padding: 24px;
    margin-top: 24px;

    .currentOnline {
      font-size: 18px;
      color: #333;
      display: flex;
      align-items: center;

      .time {
        margin-left: 29px;
        color: #ff3333;
        font-size: 12px;
      }

      .updateTips {
        color: #666;
        font-size: 12px;
      }
    }

    .currentOnline_bottom {
      display: flex;

      .currentOnline_bottom_left {
        width: 240px;
        padding-right: 60px;
        font-size: 14px;
        color: #999;
        text-align: center;

        .updateTime {
          margin-top: 60px;
          color: #333;
        }

        h2 {
          margin: 24px 0;
          font-size: 24px;
          color: #333;
        }
      }

      .currentOnline_bottom_right {
        flex: 1;
        text-align: left;

        h2 {
          padding: 24px 0 0 16px;
          color: #333;
          font-size: 16px;
          font-weight: 500;
        }

        #timeOnline {
          flex: 1;
          height: 236px;
        }
      }
    }
  }

  .visitDetail {
    .visitDetail_header {
      display: flex;
      flex-wrap: wrap;
      position: relative;
      width: 90%;
      padding-top: 24px;

      .from {
        font-size: 14px;
        color: #333;
      }

      .timeSelect {
        margin: 0 24px;
      }

      .item {
        height: 40px;
        margin-right: 24px;
        margin-bottom: 24px;
      }

      .ant-select {
        width: 100px;
      }

      .option-content {
        position: absolute;
        right: -10%;
        display: flex;
        top: 18px;
        align-items: center;
        font-size: 14px;
      }
    }
  }



  .sourceUrl {
    cursor: pointer;
    color: #1F6DED;
  }

}
</style>
<style lang="scss">
.visitDetail {


  .options {
    display: flex;
    align-items: center;
    font-size: 14px;

    .options_label {
      margin-right: 12px;
    }

    .options_content {
      margin-right: 12px;
      border: 1px solid var(--theme_button_bg_color, #1F6DED);
      display: flex;
      border-radius: 4px;

      span {
        padding: 4px 14px;
        color: #333;
        border-right: 1px solid var(--theme_button_bg_color, #1F6DED);
      }

      span:nth-last-of-type(1) {
        border-right: none;
      }

      span:hover {
        background: var(--theme_button_hover_bg_color, #4892fa);
        border-color: var(--theme_button_hover_bg_color, #4892fa);
        color: #fff;
      }

      .activeOption {
        color: #fff;
        background: var(--theme_button_bg_color, #1F6DED);
      }
    }
  }
}

.tendency_statistics_charts {
  .ant-table-column-sorters {
    max-width: 100px;
  }
}

.openorclose {
  display: flex;
  align-items: center;
}
</style>